import akshare as ak
import pandas as pd
from clickhouse_driver import Client
from datetime import datetime, timedelta

CH = Client(host='clickhouse', port=9000, database='qbot')

def create_sector_table():
    CH.execute('''
        CREATE TABLE IF NOT EXISTS sector_1m (
            ind  String,
            dt   DateTime,
            open Float32,
            high Float32,
            low  Float32,
            close Float32,
            vol   UInt64,
            amount Float64
        ) ENGINE = MergeTree()
        PARTITION BY toYYYYMMDD(dt)
        ORDER BY (ind, dt)
    ''')

def crawl_sector_1m(ind: str = "BK0475"):
    """同花顺行业指数 1 min"""
    df = ak.stock_board_industry_hist_min_em(symbol=ind, period='1')
    if df is None or df.empty:
        return
    df = df[['时间', '开盘', '最高', '最低', '收盘', '成交量', '成交额']]
    df.columns = ['dt', 'open', 'high', 'low', 'close', 'vol', 'amount']
    df['ind'] = ind
    df['dt'] = pd.to_datetime(df['dt']).dt.tz_localize('Asia/Shanghai')
    CH.insert_dataframe('INSERT INTO sector_1m VALUES', df)
